package com.example.forum.utils;

import com.example.forum.exception.ApplicationException;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * Description: 头像存储的工具类
 * User: DELL
 * Date: 2023-10-01
 * Time: 11:02
 */

public class FileUtil {

    private static final String UPLOAD_DIR = "D:\\uploads"; // 上传文件保存的目录

    /**
     * 将对应头像存入头像文件夹中,并返回头像的具体地址
     *
     * @param file
     * @return
     */
    public static String saveFile(MultipartFile file) throws IOException {
        // 确保上传目录存在
        ensureUploadDirectoryExists();
        // 生成唯一的文件名，防止文件名冲突
        String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
        // 构建文件路径
        String filePath = UPLOAD_DIR + File.separator + fileName;
        // 保存文件到磁盘
        file.transferTo(new File(filePath));
        return filePath;
    }

    private static void ensureUploadDirectoryExists() {
        File uploadDir = new File(UPLOAD_DIR);
        // 如果目录不存在，创建目录
        if (!uploadDir.exists()) {
            if (!uploadDir.mkdirs()) {
                throw new ApplicationException("头像保存的目录不存在,dir = " + uploadDir);
            }
        }
    }
}